package com.bear.fastrepair.mvvm.data.login

import android.graphics.Bitmap
import com.bear.fastrepair.entity.ResponseInfo
import com.bear.fastrepair.mvvm.data.Result
import com.blankj.utilcode.util.EncodeUtils
import com.blankj.utilcode.util.ImageUtils
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * Class that requests authentication and user information from the remote data source and
 * maintains an in-memory cache of login status and user credentials information.
 */

class LoginRepository(val dataSource: LoginDataSource) {

    // in-memory cache of the ResponseInfo object
    var user: ResponseInfo? = null
        private set

    val isLoggedIn: Boolean
        get() = user != null

    init {
        // If user credentials will be cached in local storage, it is recommended it be encrypted
        // @see https://developer.android.com/training/articles/keystore
        user = null
    }

    fun logout() {
        user = null
        dataSource.logout()
    }

    suspend fun login(
        username: String,
        password: String,
        loginType: Int,
        verificationCode: String?
    ): Result<ResponseInfo> {
        // handle login
        return withContext(Dispatchers.IO) {
            val result = dataSource.login(username, password, loginType, verificationCode)

            when (result) {
                is Result.Success -> {
                    setResponseInfo(result.data)
                }
                is Result.Error -> {
                    setResponseInfo(result.data)
                }
            }
            result
        }
    }

    suspend fun getVerificationCode(): Bitmap? {
        return withContext(Dispatchers.IO) {
            val response = dataSource.getVerificationCode()
            if (response.code == 0) {
                ImageUtils.bytes2Bitmap(EncodeUtils.base64Decode(response.data.split(",").last()))
            } else {
                null
            }
        }
    }

    private fun setResponseInfo(ResponseInfo: ResponseInfo?) {
        this.user = ResponseInfo
        // If user credentials will be cached in local storage, it is recommended it be encrypted
        // @see https://developer.android.com/training/articles/keystore
    }

    suspend fun getPersonalInfo() = withContext(Dispatchers.IO) {
        dataSource.getPersonalInfo()
    }
}